package com.suian.controller;


import com.suian.aspect.annotation.RequestLoggable;
import com.suian.client.OrderClient;
import com.suian.dao.OrderInfo;
import com.suian.dao.ProductInfo;
import com.suian.service.ProductService;
import com.suian.service.impl.ProductServiceImpl;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RequestMapping("/product")
@RestController
public class ProductController {
    private static final Logger log = LoggerFactory.getLogger(ProductController.class);
    @Autowired
    private ProductService productService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderClient orderClient;

    @RequestLoggable
    @RequestMapping("/{productId}")
    public ProductInfo getProductById(@PathVariable("productId") Integer productId){
        System.out.println("收到请求,Id:"+productId);
        return productService.selectProductById(productId);
    }

    @CircuitBreaker(name = "productController",fallbackMethod = "fallback")
    @RequestMapping("/order/{orderId}")
    public OrderInfo getOrderById(@PathVariable("orderId") Integer orderId) {
        if (orderId == 1) {
            throw  new RuntimeException("错误id");
        }
//        String url = "http://127.0.0.1:1024/order/" + orderId;
//        //获取eureka中注册的order-serviceInstance实例列表
//        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("order-service");
//        ServiceInstance serviceInstance = serviceInstanceList.get(0);
//        url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/order/" + orderId;
//
//        //通过Ribbon负载均衡调用
//        url="http://order-service/order/"+ orderId;
//        return restTemplate.getForObject(url, OrderInfo.class);
        //20250421 使用feign
        return orderClient.getOrderById(orderId);
    }

    public OrderInfo fallback(Integer orderId,Throwable ex) {
        log.error("熔断器触发 orderId: {}, Error: {}", orderId, ex.getMessage());
        return new OrderInfo();
    }
}
